<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace console\controllers;

use Yii;
use yii\helpers\Console;
use yii\console\ExitCode;
use yii\helpers\FileHelper;
use yii\console\Controller;
use yii\base\ErrorException;

/**
 * 清除命令
 *
 * 1. 清除js和css等静态资源文件脚本命令：
 * yii clear/asset
 *
 * 2. 清除runtime/cache下所有缓存命令：
 * yii clear/cache
 *
 * 3. 清除runtime下所有目录
 * yii clear/runtime
 *
 * @author cleverstone
 * @since ym2.0
 */
class ClearController extends Controller
{
    /**
     * 删除项目指定路径目录下的子目录
     * @param string $path 目录路径
     * @param boolean $isRelative 是否是相对路径
     * @return int
     * @throws ErrorException
     */
    public function actionIndex($path, $isRelative = 1)
    {
        if ($isRelative) {
            $path = '@root/' . $path;
        }

        return $this->clearDir($path);
    }

    /**
     * Deletes a subdirectory of the special directory
     * default clear the published resource bundles
     *
     * @param string $m 指定模块
     * @param string $d 指定目录
     * @return int
     * @throws ErrorException
     */
    public function actionAsset($m = 'backend', $d = 'web/assets')
    {

        return $this->clearDir('@root/' . $m . '/' . ltrim($d, '\\/'));
    }

    /**
     * 清除runtime下缓存
     * @param string $m 指定模块
     * @param string $d 指定目录
     * @return int
     * @throws ErrorException
     */
    public function actionCache ($m = 'backend', $d = 'runtime/cache')
    {
        return $this->clearDir('@root/' . $m . '/' . ltrim($d, '\\/'));
    }

    /**
     * 删除runtime下所有目录
     * @param string $m 指定模块
     * @param string $d 指定目录
     * @return int
     * @throws ErrorException
     */
    public function actionRuntime($m = 'backend', $d = 'runtime')
    {
        return $this->clearDir('@root/' . $m . '/' . ltrim($d, '\\/'));
    }


    /**
     * 清除指定目录路径下的子目录
     * @param string $dirPath
     * @return int
     * @throws ErrorException
     */
    protected function clearDir($dirPath)
    {
        try {
            $aliasPath = Yii::getAlias($dirPath);
            $realPath = realpath($aliasPath);

            if ($realPath === false) {
                throw new ErrorException("'$aliasPath' is not correct path! ");
            }

            $childDirs = FileHelper::findDirectories($realPath, ['recursive' => false]);
            if (!empty($childDirs)) {
                foreach ($childDirs as $dir) {
                    FileHelper::removeDirectory($dir);
                }
            }

            $this->stdout('The clearing is successfully. ' . PHP_EOL, Console::FG_BLUE);
            return ExitCode::OK;
        } catch (\Exception $e) {
            $this->stdout($e->getMessage(). PHP_EOL, Console::FG_RED);
            return ExitCode::UNSPECIFIED_ERROR;
        }
    }
}